package cn.tedu;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class Demo12 {
    public static void main(String[] args) {
        Scanner sca = new Scanner(System.in);
        System.out.println("请输入用户名");
        String username = sca.nextLine();
        System.out.println("请输入密码");
        String password = sca.nextLine();
        System.out.println("请输入昵称");
        String nick = sca.nextLine();
        try (Connection conn =DBUtils.getConn()){
            //使用PreparedStatement  实现注册功能  并实现用户名不能重复的功能
           /* String sql="select username from user";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                String user = rs.getString(1);
                if(user.equals(username)){
                    System.out.println("注册失败,用户名已存在");
                }else{
                    ps.executeUpdate("insert into user values(null,'"+username+"','"+password+"','"+nick+"')");
                    System.out.println("注册成功！");
                }
            }*/
            //1.查询用户名是否存在
            String sql = "select id from user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                System.out.println("用户名已存在！");
                return;
            }
            //2.实现往user表中添加数据
            String insertsql="insert into user values(null,?,?,?)";
            PreparedStatement insertPs = conn.prepareStatement(insertsql);
            insertPs.setString(1,username);
            insertPs.setString(2,password);
            insertPs.setString(3,nick);
            //执行插入
            insertPs.executeUpdate();
            System.out.println("注册完成！");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
